package com.okbihuo.perm.core.auth.handler;

import cn.hutool.extra.servlet.ServletUtil;
import com.okbihuo.perm.core.logger.publisher.LogPublisher;
import com.okbihuo.perm.core.tool.api.R;
import com.okbihuo.perm.core.tool.api.ResultCode;
import com.okbihuo.perm.core.tool.jackson.JsonUtil;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class AuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        String msg = exception.getMessage();
        if(DisabledException.class.equals(exception.getClass())) {
            msg = "账号被禁用";
        }
        if(BadCredentialsException.class.equals(exception.getClass())){
            msg = "账号或密码有误";
        }
        if(InternalAuthenticationServiceException.class.equals(exception.getClass())){
            msg = "账号未注册";
        }
        R<Object> fail = R.fail(ResultCode.UN_AUTHORIZED, "认证失败，原因："+ msg);
        LogPublisher.info("认证失败", msg);
        ServletUtil.write(response, JsonUtil.toJson(fail), "application/json;charset=UTF-8");
    }
}
